{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "tensor([[19., 25.],\n        [37., 43.]])"
     },
     "metadata": {},
     "execution_count": 1
    }
   ],
   "source": [
    "import torch\n",
    "import torch.nn as nn \n",
    "\n",
    "def corr2d(x,k):\n",
    "    h,w = k.shape\n",
    "\n",
    "    y = torch.zeros((x.shape[0] - h + 1,x.shape[1] - w + 1))\n",
    "    for i in range(y.shape[0]):\n",
    "        for j in range(y.shape[1]):\n",
    "            y[i,j] = (x[i:i + h ,j : j + w] * k).sum()\n",
    "\n",
    "    return y\n",
    "\n",
    "x = torch.tensor([[0,1,2],[3,4,5],[6,7,8]])\n",
    "k = torch.tensor([[0,1],[2,3]])\n",
    "corr2d(x,k)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Conv2D(nn.Module):\n",
    "    def __init__(self,kernel_size):\n",
    "        super(Conv2D,self).__init__()\n",
    "        self.weight = nn.Parameter(torch.randn(kernel_size))\n",
    "        self.bias = nn.Parameter(torch.randn(1))\n",
    "\n",
    "    def forward(self,x):\n",
    "        return corr2d(x,self.weight)  + self.bias"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "tensor([[1., 1., 0., 0., 0., 0., 1., 1.],\n        [1., 1., 0., 0., 0., 0., 1., 1.],\n        [1., 1., 0., 0., 0., 0., 1., 1.],\n        [1., 1., 0., 0., 0., 0., 1., 1.],\n        [1., 1., 0., 0., 0., 0., 1., 1.],\n        [1., 1., 0., 0., 0., 0., 1., 1.]])"
     },
     "metadata": {},
     "execution_count": 3
    }
   ],
   "source": [
    "x = torch.ones(6,8)\n",
    "x[:,2:6] = 0\n",
    "x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "tensor([[ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n        [ 0.,  1.,  0.,  0.,  0., -1.,  0.]])"
     },
     "metadata": {},
     "execution_count": 4
    }
   ],
   "source": [
    "k = torch.tensor([[1,-1]],dtype=torch.float)\n",
    "y = corr2d(x,k)\n",
    "y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "step 5,loss 1.586\nstep 10,loss 0.307\nweight: tensor([[ 0.8391, -0.9242]])\nbias: tensor([0.0476])\n"
    }
   ],
   "source": [
    "\n",
    "conv2d = Conv2D(kernel_size=(1,2))\n",
    "\n",
    "step = 10\n",
    "lr = 0.01\n",
    "\n",
    "for i in range(step):\n",
    "    y_hat = conv2d(x)\n",
    "    l = ((y_hat - y) ** 2).sum()\n",
    "    l.backward()\n",
    "\n",
    "    conv2d.weight.data -= lr * conv2d.weight.grad\n",
    "    conv2d.bias.data -= lr * conv2d.bias.grad\n",
    "\n",
    "    # 梯度清0\n",
    "    conv2d.weight.grad.fill_(0)\n",
    "    conv2d.bias.grad.fill_(0)\n",
    "\n",
    "    if (i + 1) % 5 == 0:\n",
    "        print(\"step %d,loss %.3f\" % (i + 1 ,l.item()))\n",
    "\n",
    "print(\"weight:\",conv2d.weight.data)\n",
    "print(\"bias:\",conv2d.bias.data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "tensor([[4., 5.],\n        [7., 8.]])"
     },
     "metadata": {},
     "execution_count": 11
    }
   ],
   "source": [
    "def pool2d(x,pool_size,mode='max'):\n",
    "    x = x.float()\n",
    "    p_h,p_w = pool_size\n",
    "    y = torch.zeros(x.shape[0] - p_h + 1,x.shape[1] - p_w + 1)\n",
    "    for i in range(y.shape[0]):\n",
    "        for j in range(y.shape[1]):\n",
    "            if mode == 'max':\n",
    "                y[i,j] = x[i:i + p_h,j:j + p_w].max()\n",
    "            elif mode == 'avg':\n",
    "                y[i,j] = x[i:i + p_h,j : j + p_w].mean()\n",
    "    return y\n",
    "\n",
    "x = torch.tensor([[0,1,2],[3,4,5],[6,7,8]])\n",
    "pool2d(x,(2,2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "tensor([[2., 3.],\n        [5., 6.]])"
     },
     "metadata": {},
     "execution_count": 12
    }
   ],
   "source": [
    "pool2d(x,(2,2),'avg')"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.7-final"
  },
  "orig_nbformat": 2,
  "kernelspec": {
   "name": "python37764bitpytorchnotebookconda6e7a8693df0d4d92aca09d521275d23a",
   "display_name": "Python 3.7.7 64-bit ('pytorch_notebook': conda)"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}